package yun.http.rechochoku;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
import yun.common.http.RequestHelper;
import yun.common.http.request.Request;
import yun.common.http.response.IResponseFactory;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

public class RecochokuApiHelper extends RequestHelper {
	private static final String TAG = "API";
	private Context mContext;
	private CookieManager mCookieManager;

	public RecochokuApiHelper(Context context, OnResponseListener l, IResponseFactory factory) {
		super(l, factory);
		mContext = context;
		CookieSyncManager.createInstance(context);
		mCookieManager = CookieManager.getInstance();

	}

	@Override
	public void sendRequest(Request request, String method) {
		Log.d(TAG, String.format("sendRequest(%s, %s)", request.getClass().getName(), method));
		super.sendRequest(request, method);

	}

	@Override
	public void cancel() {
		Log.d(TAG, "cancel()");
		super.cancel();
	}

	protected boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo active = cm.getActiveNetworkInfo();
		return active != null && active.isConnected();
	}

	@Override
	protected void saveCookie(URI uri, List<Cookie> cookies) {

		// old cookies clear
		mCookieManager.removeExpiredCookie();
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// ignore
		}

		// new cookies save
		String domain = uri.getHost();
		Cookie cookie;
		for (int i = 0; i < cookies.size(); i++) {
			cookie = cookies.get(i);
			String cookieString = cookie.getName() + "=" + cookie.getValue();
			Log.e("surosuro", cookieString);
			mCookieManager.setCookie(domain, cookieString);
			// cookie sync
			CookieSyncManager.getInstance().sync();
		}
	}
	@Override
	protected List<Cookie> getCookies(URI uri) {
		// old clear
		mCookieManager.removeExpiredCookie();
		CookieSyncManager.getInstance().sync();

		// read cookie
		List<Cookie> cookis = new ArrayList<Cookie>();
		String cookieString = mCookieManager.getCookie(uri.getHost());
		if (cookieString != null) {
			String[] keyValueSets = cookieString.split(";");
			for (String kv : keyValueSets) {

				String[] keyValue = kv.split("=");
				switch (keyValue.length) {
				case 1:
					cookis.add(new BasicClientCookie(keyValue[0], ""));
					break;
				case 2:
					cookis.add(new BasicClientCookie(keyValue[0], keyValue[1]));
					break;
				default:
					Log.w(TAG, "getCookieString()" + cookieString);
				}
			}
		}
		return cookis;
	}
}
